package scale.sim;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;

import scale.data.Scale;

public class RemoteSession implements Runnable {

	private Socket mySocket;
	private BufferedReader instream;
	private DataOutputStream outstream;
	private String inline;
	private Scale scale;

	public RemoteSession(Socket s, Scale sc) {
		this.mySocket = s;
		this.scale = sc;
	}

	@Override
	public void run() {
		try {
			// Setup input and output stream
			instream = new BufferedReader(new InputStreamReader(
					mySocket.getInputStream()));
			outstream = new DataOutputStream(mySocket.getOutputStream());

			// Send scale ID number
			outstream.writeBytes("I4 A \"3154307\"\r\n");
			
			// Loop while input string is not Q
			while (!(inline = instream.readLine().toUpperCase()).equals("Q")) {
				
				System.out.println("IN: "+ inline);
				
				// Check if RM commands have been called
				if (inline.toUpperCase().startsWith("RM")) {
					scale.scaleInputRM(inline, this);
				} else {
					String out = scale.scaleInput(inline);
					System.out.println("OUT: " + out);
					outstream.writeBytes(out);
				}
			}

		} catch (Exception e) {
			// TODO: handle exception
			System.out.println("RemoteSession terminated!");
			closeSession();
		}
	}
	
	/**
	 * Sends the scale input response to the 
	 * remote session client
	 * @param str Response
	 */
	public void sendResponse(String str){
		try {
			System.out.println("OUT: "+str);
			outstream.writeBytes(str);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 
	 * @return Remote sessions socket
	 */
	public Socket getSocket() {
		return mySocket;
	}
	
	/**
	 * Closes the connection to the scale
	 */
	public void closeSession() {
		try {
			instream.close();
			outstream.close();
			mySocket.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
}
